import { useState, useRef, useCallback, memo, useMemo } from "react"
import { Menu } from "antd"
const { SubMenu, Item } = Menu
export default function () {
    const [dataList, setDataList] = useState([
        {
            id: "1",
            name: "选项1",
            children: [
                {
                    id: "5",
                    name: "选项1-1",
                },
            ],
        },
        {
            id: "2",
            name: "选项2",
            children: [
                {
                    id: "3",
                    name: "选项2-1",
                },
                {
                    id: "4",
                    name: "选项2-2",
                },
            ],
        },
    ])

    const onSelect = (item) => {
        console.log(111, item)
    }

    return (
        <>
            <div className="main_box">
                <h1>本案例展示 react递归组件的使用 </h1>

                <div className="main_row">
                    <Tree data={dataList}></Tree>
                    <p>递归组件：递归组件就是组件内部自己调用自己，在组件内部自己调用自己，必须有一个明确的结束条件，否则会陷入死循环。递归组件常用于树形控件中，如树形菜单、树形目录等。</p>
                </div>

                <div className="main_row">
                    <TreeMenu data={dataList} onSelect={onSelect}></TreeMenu>
                    <p>上面是用antd的Menu菜单做的递归组件(当前版本antd5+已废弃submenu写法，统一用items,不用递归组件了)，这里仅做演示用。不知道是不是因为废弃的原因，Menu的事件获取不到参数。</p>
                </div>
            </div>
        </>
    )
}

// 递归组件
const Tree = ({ data }) => {
    return (
        <ul className="tree_box">
            {data.map((item) => (
                <li key={item.id} className="tree_item">
                    {/* 没有子节点，就渲染name */}
                    {item.name}
                    {/* 有子节点，就递归 */}
                    {item.children && item.children.length > 0 && <Tree data={item.children} />}
                </li>
            ))}
        </ul>
    )
}

// antd menu递归组件
const TreeMenu = ({ data, onSelect }) => {
    const [openKeys, setOpenKeys] = useState([]) // 保存展开的菜单
    const [selectedKeys, setSelectedKeys] = useState([]) // 保存选中的菜单

    const handleSelect = useCallback(
        (node) => {
            setSelectedKeys([node.id])
            onSelect?.(node)
        },
        [onSelect]
    )

    // 递归生成菜单项
    const generateMenuItems = (items) => {
        return items.map((item) => {
            if (item.children && item.children.length > 0) {
                return (
                    <SubMenu key={item.id} title={item.name}>
                        {generateMenuItems(item.children)}
                    </SubMenu>
                )
            }
            return (
                <Item key={item.id} onClick={() => handleSelect(item)}>
                    {item.name}
                </Item>
            )
        })
    }

    return (
        <Menu mode="inline" openKeys={openKeys} onOpenChange={setOpenKeys} selectedKeys={selectedKeys}>
            {generateMenuItems(data)}
        </Menu>
    )
}
